package com.cliff.babyshop.controller;

import com.cliff.babyshop.VO.ProductInfoVO;
import com.cliff.babyshop.VO.ProductVO;
import com.cliff.babyshop.VO.ResultVO;
import com.cliff.babyshop.entity.ProductCategory;
import com.cliff.babyshop.entity.ProductInfo;
import com.cliff.babyshop.service.impl.CategoryServiceImpl;
import com.cliff.babyshop.service.impl.ProductServiceImpl;
import com.cliff.babyshop.util.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductServiceImpl productService;
    @Autowired
    private CategoryServiceImpl categoryService;

    @GetMapping(value = "/list")
    public ResultVO list() {
        List<ProductInfo> productInfoList = productService.findUpAll();
        //java8新特性 lembda
        List<Integer> productCagegoryList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(productCagegoryList);

        List<ProductVO> productVOList = new ArrayList<ProductVO>();
        for (ProductCategory productCategory : categoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());

            List<ProductInfoVO> productInfoVOList = new ArrayList<ProductInfoVO>();
            for (ProductInfo productInfo : productInfoList) {
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVOUtil.success(productVOList);
    }
}
